--
-- @Author:      name
-- @DateTime:    2018-03-30 23:05:48
-- @Description: 客户端消息的处理

local skynet = require "skynet"
local log = require "Logger"
local config = require "configquery"
local crypt = require "skynet.crypt"


local ClientHandler = class("ClientHandler")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function ClientHandler:ctor(message_dispatch, node_message)

	self.message_dispatch = message_dispatch	
	self.auth_services = {} --处理事务的service
	self.node_message = node_message

	self:register()
end

--注册本服务里的消息
function ClientHandler:register()
	
	self.message_dispatch:registerSelf('client_req', handler(self,self.clientReq))
	self:registerSelf('userRegisterReq')
	self:registerSelf('userLoginReq')
	-- self:registerSelf('userAuthLoginReq')
end

function ClientHandler:registerSelf(message_name)
	if not self[message_name] then 
		log.error("__registerSelf_没有注册函数回调____",message_name)
	end
	self.message_dispatch:registerSelf(message_name, handler(self,self[message_name]))
end

---------------------------------------------------------
-- CMD
---------------------------------------------------------

--用户注册
function ClientHandler:userRegisterReq(data)
-- //用户注册
-- message MSG_UserRegister  
-- {
-- 	required string		version			= 1;	// 版本号
-- 	required string 	mac_addr   		= 2;	// MAC物理地址(UUID)
-- 	required string		package_name	= 3;	// 游戏包名
-- 	required uint32		device_type		= 4;	// 手机设备
-- 	required uint32		channel_id		= 5;	// 渠道标识
-- 	required uint32		login_type  	= 6;	// 登录类型
-- 	required string  	account			= 7;	// 帐号
-- 	optional string		password		= 8;	// 密码
-- 	optional string		nickname		= 9;	// 昵称
-- 	optional uint32		sex				= 10;	// 性别
-- 	optional uint32		face_id			= 11;	// 头像标识
-- 	optional string		invite_code		= 12;	// 注册邀请码
-- 	optional uint32		reference_id	= 13;	// 引荐人ID
-- 	optional uint32		site_code		= 14;	// 站点标识
-- 	optional string		nation_code 	= 15;	// 国家
-- 	optional string		city_code 		= 16;	// 城市
-- required uint32		domain_id		= 17; 	//平台ID
-- }
	print("__________userRegisterRes___",data)
	local res = self.node_message:callDbProxy("get_user", nil, {{username=data.account}})
	-- print("________get_user_______",res)
	if res and next(res) then 
		--用户已存在，不能注册	
		local result  = {
			userRegisterRes={
				error_code = 1,
				error_msg = "注册失败，帐号已存在"
			}
		}			
		return result
	else
		local time = os.time()
		local token = crypt.base64encode(tostring(time))			
		local user_info = {
			domain_id = data.domain_id,
			device = data.device_type,
			channel_id = data.channel_id,
			username = data.account,
			password = data.password,
			nickname = data.nickname,			
			face_id = data.face_id,
			invite_code = data.invite_code,
			token = token,		--token写入数据库	
		}
		--添加到数据库
		local add_result = self.node_message:callDbProxy("add_user",user_info)
		local res
		if add_result then 			
			res = self.node_message:callDbProxy("get_user" ,nil, {{username=data.account}})	
		end
		local body
		-- print("________res_______",res)
		if res and next(res) then 
		    --把相关信息写到redis
		    local user_id = res.user_id
		    local info = {
		        user_id = user_id,
		        token = token,		        
		    }
		    self.node_message:callDbRedis("hmset", { "gate_info:" .. user_id, info}, user_id)			
			--注册成功
			local result  = {
				userLoginRes = {
					user_info = {
						user_id = res.user_id,
						account = res.username,
						nickname = res.nickname,
						diamond = res.diamond,
						money = res.money,
						face_id = res.face_id,
						bind_phone = res.mobile,
					},
					token = token,
					server_addr = "127.0.0.1:12201",
				}
			}			
			return result
		else
			--注册失败
			local result  = {
				userRegisterRes = {
					error_code = 1,
					error_msg = "注册失败，帐号已存在2"
				},
			}			
			return result
		end
		
	end
end

function ClientHandler:userLoginReq(data)
	print("__________userLoginReq___",data)	

	local res = self.node_message:callDbProxy("get_user", nil, {{username=data.account}})	
	if not res or not next(res) then 
		assertEx(false, "userLoginRes", 1)
	end
	if data.password~=res.password then 
		assertEx(false, "userLoginRes", 2)
	end	
	--密码正确
	--生成token
	local time = os.time()
	local token = res.token
	local tokenTime = crypt.base64decode(token) or 0
	local user_id = res.user_id
	-- print("____user_id_______", user_id,time, tokenTime )
	if time > tokenTime + 60*5 then 
		token = crypt.base64encode(tostring(time))
		local user = {
			username = res.username,
			token = token,
		}
		--token写入数据库
		self.node_message:sendDbProxy("update_user", user, {{username=res.username}} )			
	    --把相关信息写到redis		 
	    local info = {
	        user_id = user_id,
	        token = token,		        
	    }
	    self.node_message:callDbRedis("hmset", {"gate_info:" .. user_id, info}, user_id)		
	else
		--
		print("____用户时间比token时间小____")		
	end
	--请求分配游戏网关
    local info = {
        user_id = user_id,
        token = token,		        
    }
	local assign_result = self.node_message:callZoneProxy("assign_server_req", info)
	print("___assign_result__",assign_result)
	local gate_server_addr = assign_result.server_addr
	if data.contype=="websocket" then 
		gate_server_addr = gate_server_addr ..":".. assign_result.server_wport
	else
		gate_server_addr = gate_server_addr ..":".. assign_result.server_port
	end
	local result  = {
		userLoginRes = {
			user_info = {
				user_id = res.user_id,
				account = res.username,
				nickname = res.nickname,					
				diamond = res.diamond,
				money = res.money,				
				face_id = res.face_id,					
				bind_phone = res.mobile,
			},
			token = token,
			server_addr = gate_server_addr,
		},		
	}
	return result
	
end


--从网关发来的消息
function ClientHandler:clientReq(data)
	print("_______loginserver___clientReq___",data)	
	local command = data.command
	local res = self.message_dispatch:dispatchSelfMessage(data.callback, data.message_body)
	return res
end



return ClientHandler